package com.asohofrucol.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;

import com.asohofrucol.dto.ParameterLocationDTO;
import com.asohofrucol.dto.RuatRegisterDTO;
import com.asohofrucol.dto.util.RuatHelperDto;
import com.asohofrucol.model.Ruat;
import com.asohofrucol.service.UserOwnerService;

/**
 * 
 * @author iván
 * 
 *         Esta Clase es un servicio pero adaptado a la interfaz web, mediante
 *         el metodo load, la tabla maneja paginacion en el lado del servidor
 */
public class LazyRuatRegisterDataModel extends LazyDataModel<RuatRegisterDTO> {

	private static final long serialVersionUID = 1L;

	@Autowired
	private UserOwnerService userOwnerService;
	@Autowired
	private ParameterLocationDTO cacheLocation;

	@Override
	public Object getRowKey(RuatRegisterDTO register) {
		return register.getId();
	}

	@Override
	public RuatRegisterDTO getRowData(String rowKey) {
		System.out.println("rowKey " + rowKey);
		return userOwnerService.findOne(Long.parseLong(rowKey));
	}

	@Override
	public List<RuatRegisterDTO> load(int first, int pageSize,
			String sortField, SortOrder sortOrder, Map<String, String> filters) {

		System.out.println(first / pageSize);
		int pageIndex = first / pageSize;
		/**
		 * Esto es una prueba de usabilidad
		 */
		if (filters.isEmpty()) {
			return new ArrayList<RuatRegisterDTO>();
		}

		/**
		 * Fin prueba usabilidad
		 */
		Page<Ruat> pageRuats = userOwnerService.load(pageIndex, pageSize,
				sortField, sortOrder, filters);
		List<Ruat> listRuats = pageRuats.getContent();
		this.setRowCount((int) pageRuats.getTotalElements());

		List<RuatRegisterDTO> listRuatRegisterDTO = new ArrayList<RuatRegisterDTO>();

		System.out.println("tamaño arreglo de opciones "
				+ cacheLocation.getLocationDesc().size());
		for (Ruat ruat : listRuats) {
			RuatRegisterDTO ruatRegisterDTO = new RuatRegisterDTO();
			ruatRegisterDTO = RuatHelperDto.convertToDto(ruat);
			ruatRegisterDTO.setVillageDesc(cacheLocation.getLocationDesc().get(
					ruat.getVillage()));
			ruatRegisterDTO.setMunicipalityDesc(cacheLocation.getLocationDesc()
					.get(ruat.getMunicipality()));
			ruatRegisterDTO.setDepartamentDesc(cacheLocation.getLocationDesc()
					.get(ruat.getDepartament()));

			ruatRegisterDTO.setFarmVillageDesc(cacheLocation.getLocationDesc()
					.get(ruat.getFarmVillage()));
			ruatRegisterDTO.setFarmMunicipalityDesc(cacheLocation
					.getLocationDesc().get(ruat.getFarmMunicipality()));
			ruatRegisterDTO.setFarmDepartamentDesc(cacheLocation
					.getLocationDesc().get(ruat.getFarmDepartament()));

			listRuatRegisterDTO.add(ruatRegisterDTO);
		}
		return listRuatRegisterDTO;
	}

}
